<?php
namespace control;

/*
*生产流转卡类
*/

class machiningCardClass extends adIndexClass
{
    private const page = 'machiningCard';
    private const table = 'machining_card';
    private const tableMx = 'machining_card_detail';
    private const title = '生产流转卡';

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'orderNo'          => [
                        'name'  => "单据编号",
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'code'  => [
                        'name'  => '物料编码',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'name'         => [
                        'name'  => '物料名称',
                        'width' => 150,
                    ],
                    'model'          => [
                        'name'  => '规格型号',
                        'width' => 150,
                    ],
                    'unit'          => [
                        'name'  => '单位',
                        'width' => 60,
                    ],
                    'num'          => [
                        'name'  => '生产数量',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'inStockNum'          => [
                        'name'  => '已生产入库数量',
                        'width' => 120,
                    ],
                    'notInNum'          => [
                        'name'  => '未入库数量',
                        'width' => 100,
                    ],
                    'completionRate'          => [
                        'name'  => '生产完成率',
                        'width' => 100,
                    ],
                    'sourceNo'          => [
                        'name'  => '关联单据',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'startDate'          => [
                        'name'  => '计划开工时间',
                        'width' => 120,
                    ],
                    'endDate'          => [
                        'name'  => '计划完工时间',
                        'width' => 120,
                    ],
                    'recordDate'          => [
                        'name'  => '单据日期',
                        'width' => 120,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "单据编号" => text(array("name" => "orderNo")),
                    "物料名称"   => text(array("name" => "materialName")),
                    "物料编码"   => text(array("name" => "materialCode")),
                ],
                [
                    '生产线'  => selectMultiple(["name" => "lineId", 'table' => "product_line", 'sqlId' => 'id', 'where' => "coid = '" . self::$coid . "'", 'sqlField' => 'name', 'class' => 'width200']),
                    "单据日期" => text(array("name" => "createTime", 'laydate' => ['type' => 'date', 'range' => '~'])),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        $url = root . "control/adIndex.html?cla=" . self::page;
        if ($this->power(self::page, "export")) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','exportFrame',{cla:'".self::page."'})\">导出</span>";
        }
        if ($this->power(self::page, "print")) {
            $button .= " <span onclick=\"batchPrint('" . $this->get('cla') . "')\" class='spanButton'>批量打印</span>\n";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }


    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            "a.orderNo" => $this->post('orderNo'),
            "b.name" => $this->post('materialName'),
            "b.code" => $this->post('materialCode'),
        );
        //全等查询数组
        $equal = array(
            'a.coid' => self::$coid,
            "a.lineId" => $this->post('lineId'),
        );
        $and = '';
        if ($this->post('createTime')) {
            $and .= self::timeComparison($this->post('createTime'), 'date', 'c.recordDate');
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'recordDate desc,orderNo',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array(
            "table" => self::table . ' as a join material as b on a.materialId = b.id join machining_order as c on a.sourceId = c.id',
            'field' => "a.*,b.name,b.code,b.model",
            "where" => $where,
            "order" => $orderBy['orderBy']
        ));
        $_SESSION[self::page]['sql'] = $page['fullSql'];
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        $url = root . "control/adIndex.html?cla=" . self::page;
        $machiningObj = new machiningOrderClass();
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
                 'print' => array('title' => '打印', 'click' => "window.open('" . root . "control/adIndex.html?cla=" . self::page . "&fun=printPage&id={$array['id']}')"),
                'track' => array("title" => "单据追踪", "click" => "newIframe('单据追踪','" . root . "control/adIndex.html?cla=orderTrack&fun=home&orderType=生产流转卡&id=" . $array['id'] . "')"),
            );
            $machiningOrder = query('machining_order', "id = '$array[sourceId]'");
            //已生产入库的数量
            $inStockNum = $machiningObj->inStockNum($array['sourceMxId'], $array['unit']);
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'num':
                        $row[] = self::lostZero($array['num'],'numPrecision');
                        break;
                    case 'inStockNum':
                        $row[] = self::lostZero($inStockNum, 'numPrecision');
                        break;
                    case 'notInNum':
                        $row[] = self::lostZero($array['num'] - $inStockNum, 'numPrecision');
                        break;
                    case 'completionRate':
                        $row[] = $machiningObj->formatRatio($inStockNum, $array['num']);
                        break;
                    case 'startDate':
                    case 'endDate':
                    case 'recordDate':
                        $row[] = $machiningOrder[$key];
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        $totalQuery = find([
            'table'  => self::table . ' as a join material as b on a.materialId = b.id join machining_order as c on a.sourceId = c.id',
            'single' => $where,
            'field'  => "ifnull(sum(a.num),0) as num",
        ]);
        // 生产入库数量
        // 单位转换 先将inventory_detail的数量转为主单位数量(CASE WHEN mx.unit = b.unit_one THEN mx.num*b.unit_one_num WHEN mx.unit = b.unit_two THEN mx.num*b.unit_two_num ELSE mx.num END)
        // 再将主单位数量转为machining_order_mx的单位数量（主单位数量/machining_order_mx的单位转换数量）
        $inventory = find(array(
            'table'  => self::table . ' as a join material as b on a.materialId = b.id join machining_order as c on a.sourceId = c.id join machining_in_order_detail as miod on miod.sourceId = a.sourceMxId join inventory_detail as mx on mx.sourceId = miod.id ',
            'single'=>$where,
            'field'=>"ifnull(SUM((CASE WHEN mx.unit = b.unit_one THEN mx.num*b.unit_one_num WHEN mx.unit = b.unit_two THEN mx.num*b.unit_two_num ELSE mx.num END)/(CASE WHEN a.unit = b.unit_one THEN b.unit_one_num WHEN a.unit = b.unit_two THEN b.unit_two_num ELSE 1 END)),0) AS num"
        ));
        $total    = [
            'num'        => self::lostZero($totalQuery['num'], 'numPrecision'),
            'inStockNum'        => self::lostZero($inventory['num'], 'numPrecision'),
            'notInNum' => self::formattingFigure($totalQuery['num'] - $inventory['num'], 'numPrecision'),
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
        //返回
        $json['html'] = $page['hint'] . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**
     * 导出
     */
    public function exportData()
    {
        $templateId = $this->get('templateId');
        $checkedId = $this->get('checkedId')?explode(',',$this->get('checkedId')):[];
        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] = '你还没有导出的权限';
        }  else {
            $machiningObj = new machiningOrderClass();
            $data = [];
            /***********标题**********/
            $title =[];
            $tempFieldAll = importTemplateClass::templateField(self::page, 'exportFieldInit', id:$templateId);
            foreach ($tempFieldAll as $array) {
                if ($array['display']){
                    $title[] = $array['aliasName'];
                }
            }
            //判断是否选中导出
            if (!self::is_null_array($checkedId)){
                $result = find(array(
                    "table" => self::table . ' as a join material as b on a.materialId = b.id join machining_order as c on a.sourceId = c.id',
                    'field' => "a.*,b.name,b.code,b.model",
                    "where" => "a.id in ('".implode("','", $checkedId)."') order by recordDate desc,orderNo desc",
                ))['array'];
            }else{
                $sql   = $_SESSION[self::page]['sql'];
                $result   = sqlFind($sql);
            }
            //导出数据生成
            foreach ($result as $array){
                $column = [];
                $machiningOrder = query('machining_order', "id = '$array[sourceId]'");
                //已生产入库的数量
                $inStockNum = $machiningObj->inStockNum($array['sourceMxId'], $array['unit']);
                $all = find(array('table' => self::tableMx, 'where' => "orderId = '$array[id]' order by list"));
                foreach ($all['array'] as $index => $val) {
                    $process = query('process', "id = '$val[processId]'");
                    $num = find(array('table' => 'process_report', 'where' => "sendId = '$val[id]' and state = '已确认'", 'sum' => "yield"));
                    $badNum = find(array('table' => 'process_report', 'where' => "sendId = '$val[id]' and state = '已确认'", 'sum' => "badNum"));
                    foreach ($tempFieldAll as $templateField){
                        if ($templateField['display']){
                            $column[] = match ($templateField['columnName']){
                                '单据编号'=>$array['orderNo'],
                                '物料编码'=>$array['code'],
                                '物料名称'=>$array['name'],
                                '规格型号'=>$array['model'],
                                '单位'=>$array['unit'],
                                '生产数量'=>self::lostZero($array['num'], 'numPrecision'),
                                '已生产入库数量'=>self::lostZero($inStockNum, 'numPrecision'),
                                '未入库数量'=>self::lostZero($array['num'] - $inStockNum, 'numPrecision'),
                                '生产完成率'=>$machiningObj->formatRatio($inStockNum, $array['num']),
                                '关联单据'=>$array['sourceNo'],
                                '计划开工时间'=>$machiningOrder['startDate'],
                                '计划完工时间'=> $machiningOrder['endDate'],
                                '单据日期'=>$machiningOrder['recordDate'],
                                '工序名称'=>  $process['name'],
                                '报工数量'=>   self::lostZero($num,'numPrecision'),
                                '合格品数量'=> self::lostZero($num-$badNum,'numPrecision'),
                                '不合格数量'=> self::lostZero($badNum,'numPrecision'),
                                default=>'',
                            };
                        }
                    }
                    $data[] = $column;
                }
            }
            $text = $this->control['name'] . "导出了生产流转卡";
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $data, "生产流转卡.xlsx");
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));
    }

    /*详情页*/
    public function detail(): string
    {
        $info = query(self::table, " id = '{$this->get('id')}'");
        if (empty($info['id'])) {
            $html = '未找到此' . self::title;
        } else {
            //菜单
            $data = array(
                "id" => $info['id'],
            );

            $button = [];
            //按钮
            $button[] = [
                "name" => "打印",
                "type" => "点击事件",
                "fun" => "window.open('" . root . "control/adIndex.html?cla=" . self::page . "&fun=printPage&id={$info['id']}')",
            ];
            $button[] = [
                "name" => "单据追踪",
                "type" => "顶部页卡",
                "title" => "单据追踪",
                "url" => $this->root . "control/adIndex.html?cla=orderTrack&fun=home&orderType=生产流转卡&id=" . $info['id'],
            ];
            $tr[] = ['工序名称', '报工数量', '合格品数量', '不合格数量', '备注'];
            $result = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by list"));
            $total = ['report'=>0,'bad'=>0,'pass'=>0];
            foreach ($result['array'] as $index => $array) {
                $process = query('process', "id = '$array[processId]'");
                $num = find(array('table' => 'process_report', 'where' => "sendId = '$array[id]' and state = '已确认'", 'sum' => "yield"));
                $badNum = find(array('table' => 'process_report', 'where' => "sendId = '$array[id]' and state = '已确认'", 'sum' => "badNum"));
                $tr[] = [
                    $process['name'],
                    self::lostZero($num,'numPrecision'),
                    self::lostZero($num-$badNum,'numPrecision'),
                    self::lostZero($badNum,'numPrecision'),
                    textarea(array('name'=>'text[]','other'=>"onblur='setVal(this)' data-id='$array[id]'",'value'=>$array['text'],'class'=>'textarea'))
                ];
                $total['report'] += $num;
                $total['bad'] += $badNum;
                $total['pass'] += $num - $badNum;
            }
            $total_tr = [
                1 => self::formattingFigure($total['report'], 'numPrecision'),
                2 => self::formattingFigure($total['pass'], 'numPrecision'),
                3 => self::formattingFigure($total['bad'], 'numPrecision'),
            ];
            $material = query('material', " id = '$info[materialId]'");
            //生成表单
            $data['button'] = $this->tableShowButton($button);
            $data['html'] = $this->tableShow(array(
                '基本信息' => array(
                    array(
                        "物料编码" => $material['code'],
                        "物料名称" => $material['name'],
                        "规格型号" => $material['model'],
                        "单位" => $info['unit'],
                    ),
                    array(
                        "生产数量" => self::lostZero($info['num'],'numPrecision'),
                        "单据编号" => $info['orderNo'],
                        "制单人" => self::findStaff($info['stid']),
                    ),
                ),
            ));
            $data['html'] .= $this->detailList([
                'title' => '工序',
                'html' => $this->listTable(array('tr' => $tr, 'showSort' => true, 'total' => $total_tr)),
            ]);
            //生成页面
            $html = $this->tab($data).$this->js();
        }
        //返回
        return $html;
    }

	public function js(){
        return <<<eof
<script>
function setVal(e){
    let id = $(e).data('id');
    $.post(root+'control/adIndex.html?cla=machiningCard&fun=setText',{text:e.value,id:id},function(res) {
        if (res.warn===2){
             msg('添加成功');
        }else{
            msg(res.warn,'error');
        }
    },'json')
}
</script>
eof;

    }
    public function setText(){
        $id = $this->post('id');
        $text = $this->post('text');
        $mx = query(self::tableMx,"id = '$id'");
        if (!$this->power(self::page,'see')){
            $json['warn'] = '您还没有生产流转卡的查看权限';
        }elseif(empty($id) || empty($mx['id'])){
            $json['warn'] = '未找到ID';
        }else{
            $json['warn'] = self::update(array('table'=>self::tableMx,"field"=>['text'=>$text],'where'=>"id = '$mx[id]'"));
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                $json['warn'] = 2;
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】的备注为【'.$text.'】';
                $this->logText(["type" => self::page, "text" => $text]);
            }
        }
        return json_encode($json, 320);
    }
	/**
	 * 批量打印
	 *
	 * @return string
	 */
	public function batchPrint(): string
	{
		$lists = $this->get('lists');
		if(empty($lists)){
			exit('参数错误');
		}else{
			$listId = base64_decode($lists, true);
			$array = explode(',', $listId);
			$data = [];
			foreach ($array as $id){
				$data[] = static::printPage($id, false);
			}
			return (new printTemplateClass())->start(self::page, $data);
		}
	}

	/**
	 * 打印
	 *
	 * @return string
	 */
	public function printPage($param = '', $isReturn = true): string|array
	{
		$id                  = $param ?: $this->get('id');
		$info                = query(self::table, " id = '$id'");
        $machiningOrder  = query('machining_order',"id = '$info[sourceId]'");
        $material = query('material',"id = '$info[materialId]'");
        $info['companyName'] = query('company', "coid = '" . self::$coid . "'")['name']; //公司名称
        $info['title'] = self::title;
        $info['printTime'] = $this->time;
        $info['stid'] = self::findStaff($info['stid']);
        $info['checkId'] = '';
        $info['num'] = self::lostZero($info['num'],'numPrecision');
        $info['materialName'] =$material['name'];
        $info['materialCode'] =$material['code'];
        $info['materialModel'] =$material['model'];
        $info['startDate'] =$machiningOrder['startDate'];
        $info['endDate'] = $machiningOrder['endDate'];
        $info['qr'] = "source=" . self::table . "&id=" . $info['id'];
        $info['processTitle'] = '工序';
        $detail = find(['table' => self::tableMx, 'where' => "orderId = '$info[id]' order by list asc"])['array'];
        $items = [];
        $x = 1;
        foreach ($detail as $array) {
            $process = query('process', "id = '$array[processId]'");
            $num = find(array('table' => 'process_report', 'where' => "sendId = '$array[id]' and state = '已确认'", 'sum' => "yield"));
            $badNum = find(array('table' => 'process_report', 'where' => "sendId = '$array[id]' and state = '已确认'", 'sum' => "badNum"));
            $items[] = [
                'no' => $x,
                'name'=>$process['name'],
                'num'=>self::lostZero($num,'numPrecision'),
                'goodNum'=>self::lostZero($num-$badNum,'numPrecision'),
                'badNum'=>self::lostZero($badNum,'numPrecision'),
                'text'=>neirong($array['text'])
            ];
            $x++;
        }
        $info['detail'] = $items;
	    if ($isReturn) {
		    return (new printTemplateClass())->start(self::page, $info);
	    } else {
		    return $info;
	    }
    }

    /**
     * 导出模板字段初始化
     * @return array[]
     */
    public function exportFieldInit($classify=''): array
    {
        return match ($classify) {
            default=>  [
                [
                    'columnName'=>'单据编号',
                    'aliasName'=>'单据编号',
                ],
                [
                    'columnName'=>'物料编码',
                    'aliasName'=>'物料编码',
                ],
                [
                    'columnName'=>'物料名称',
                    'aliasName'=>'物料名称',
                ],
                [
                    'columnName'=>'规格型号',
                    'aliasName'=>'规格型号',
                ],
                [
                    'columnName'=>'单位',
                    'aliasName'=>'单位',
                ],
                [
                    'columnName'=>'生产数量',
                    'aliasName'=>'生产数量',
                ],
                [
                    'columnName'=>'已生产入库数量',
                    'aliasName'=>'已生产入库数量',
                ],
                [
                    'columnName'=>'未入库数量',
                    'aliasName'=>'未入库数量',
                ],
                [
                    'columnName'=>'生产完成率',
                    'aliasName'=>'生产完成率',
                ],
                [
                    'columnName'=>'关联单据',
                    'aliasName'=>'关联单据',
                ],
                [
                    'columnName'=>'计划开工时间',
                    'aliasName'=>'计划开工时间',
                ],
                [
                    'columnName'=>'计划完工时间',
                    'aliasName'=>'计划完工时间',
                ],
                [
                    'columnName'=>'单据日期',
                    'aliasName'=>'单据日期',
                ],
                [
                    'columnName'=>'工序名称',
                    'aliasName'=>'工序名称',
                ],
                [
                    'columnName'=>'报工数量',
                    'aliasName'=>'报工数量',
                ],
                [
                    'columnName'=>'合格品数量',
                    'aliasName'=>'合格品数量',
                ],
                [
                    'columnName'=>'不合格数量',
                    'aliasName'=>'不合格数量',
                ],
            ]
        };
    }
}

